package server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;

import javax.jdo.PersistenceManager;

import model.TrackIp;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.google.appengine.api.datastore.Text;

import data.Data;


public class GetTrackIp {
	public GetTrackIp(TrackIp ip)
	{
		String content = "";
		try {
			
			URL dataURL = new URL("http://whatismyipaddress.com/ip/"+ip.getIp());
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(dataURL.openStream(), Charset.forName("iso-8859-1")));
			
			while(1==1)
			{
				String str = reader.readLine();
				if(str==null) break;
				content+=str;
				
			}
			
			Document doc = Jsoup.parse(content);

			try {
				PersistenceManager psm = Data.get().getPersistenceManager();
				ip.setJsp(new Text(doc.select("div[id=section_content]").select("table").get(0).select("td").get(1).text()));
				ip.setOrganization(new Text(doc.select("div[id=section_content]").select("table").get(0).select("td").get(2).text()));
				ip.setProxy(new Text(doc.select("div[id=section_content]").select("table").get(0).select("td").get(3).text()));
				ip.setType(new Text(doc.select("div[id=section_content]").select("table").get(0).select("td").get(4).text()));
				ip.setAssignment(new Text(doc.select("div[id=section_content]").select("table").get(0).select("td").get(5).text()));
				ip.setCountry(new Text(doc.select("div[id=section_content]").select("table").get(1).select("td").get(0).text()));
				ip.setState(new Text(doc.select("div[id=section_content]").select("table").get(1).select("td").get(1).text()));
				ip.setCity(new Text(doc.select("div[id=section_content]").select("table").get(1).select("td").get(2).text()));
				
				psm.makePersistent(ip);

			} catch (Exception e) {
				// TODO: handle exception
			}

		} catch (Exception e) {
			
			e.printStackTrace();
		}

	}
//	public static void main( String args[])
//	{
//		new GetTrackIp("50.17.209.163");
//	}
}
